package com.mingda.weathermagiccenter.task;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mingda.weathermagiccenter.config.hefengconfig.*;
import com.mingda.weathermagiccenter.dto.hefeng.*;
import com.mingda.weathermagiccenter.pojo.*;
import com.mingda.weathermagiccenter.service.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;

import java.net.http.HttpHeaders;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Async
@Slf4j
@Configuration // 1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@ConditionalOnProperty(prefix = "weatherconfig",name = "enabled",havingValue = "true")
public class InsertHeFengTask {


    @Autowired
    private WeatherConfigBean configBean;

    @Autowired
    private WsStationService wsStationService;
    @Autowired
    private WsStationDataCurService wsStationDataCurService;
    @Autowired
    private WsStationDataService wsStationDataService;

    @Autowired
    private WsStationFcDataService wsStationFcDataService;

    @Autowired
    private WsStationFcDataCurService wsStationFcDataCurService;

    @Autowired
    private WsAlarmDataService wsAlarmDataService;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 定时更新和风天气
     * 上报
     */
    @Async
    @Scheduled(cron = "${weatherconfig.cron}")
    public void downloadweather() throws InterruptedException {
        log.info("和风实时天气任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        for (String locationid : configBean.getLocation()) {
            loadWeather(locationid);
        }
    }



    @Async
    @Scheduled(cron = "${weatherconfig.fccron}")
    public void downloadfcweather() throws InterruptedException {
        log.info("和风预报天气任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());
        for (String locationid : configBean.getLocation()) {
            loadFcWeather(locationid);
        }
    }


    @Async
    @Scheduled(cron = "${weatherconfig.alarmcron}")
    public void downloadalarm() throws InterruptedException {
        log.info("和风预警任务开始 : " + LocalDateTime.now().toLocalTime() + "\r\n线程 : " + Thread.currentThread().getName());

        List<WeatherWarningBean> citylist =  loadwaringcity();
        List<String> locationIds = citylist.stream()
                .map(WeatherWarningBean::getLocationId)
                .collect(Collectors.toList());

        LambdaQueryWrapper<WsStation> wrapper = new LambdaQueryWrapper<WsStation>();
        wrapper.eq(WsStation::getAlarmflag,"1");

        if (!locationIds.isEmpty()) {
            wrapper.in(WsStation::getStationkey, locationIds);
        }


        List<WsStation> list = wsStationService.list(wrapper);
        //获得查询
        for (WsStation ws : list) {
            loadAlarm(ws);
        }
    }





    public void loadWeather(String orgid)  {
        SimpleDateFormat sdfresult = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat md = new SimpleDateFormat("MM-dd");
        try {

            LambdaQueryWrapper<WsStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WsStation::getStationtype,"4").likeRight(WsStation::getOrgid,orgid);
            List<WsStation>  weatherLocations =  wsStationService.list(queryWrapper);
            log.info("==============更新天气信息"+orgid+" ("+weatherLocations.size() + ")======================");
            for (WsStation w : weatherLocations) {
                WeatherResult weatherResult = new WeatherResult();
                String url = configBean.getWeatherurl() + "location={location}&key={key}";
                //设置请求头
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("location",w.getLon() + "," +w.getLat());
                paramMap.put("key",configBean.getKey());


                ResponseEntity<WeatherResult> responseEntity = restTemplate.getForEntity(url, WeatherResult.class,paramMap);
             //   String str = responseEntity.getBody();
                 weatherResult = responseEntity.getBody();
               if (weatherResult != null && weatherResult.getNow() != null) {
                   try {
                       List<WsStationData> datalist = new ArrayList<WsStationData>();
                       List<WsStationDataCur> list2 = new ArrayList<WsStationDataCur>();
                       WeatherBean bean = weatherResult.getNow();
                       WsStationData ws = new WsStationData();
                       ws.setStationkey(w.getStationkey());
                       ws.setPres(Float.parseFloat(bean.getPressure()));
                       ws.setHumi(Float.parseFloat(bean.getHumidity()));
                       ws.setPrec(Float.parseFloat(bean.getPrecip()));
                       ws.setWepTxt(bean.getText());
                       ws.setTemp(Float.parseFloat(bean.getTemp()));
                       ZonedDateTime zonedDateTime = ZonedDateTime.parse(bean.getObsTime());
                       LocalDateTime localDateTime = zonedDateTime.toLocalDateTime();
                       ws.setTimebase(roundToNearestHour(localDateTime)); //时间四舍五入
                       ws.setWin10Dir(Integer.parseInt(bean.getWind360()));

                       float windSpeedKmH = Float.parseFloat(bean.getWindSpeed());
                       float windSpeedMps = windSpeedKmH / 3.6f;
                       ws.setWin10Vel(windSpeedMps);
                       String month = bean.getObsTime().replace("-", "");
                       month = month.substring(0, 6);
                       ws.setMonth(month);   //表分区月份 比填写
                       datalist.add(ws);
                       //插入当前数据表
                       WsStationDataCur wsc = new WsStationDataCur();
                       try {
                           BeanUtils.copyProperties(wsc,ws);
                           list2.add(wsc);
                       } catch (Exception e) {

                       }

                       wsStationDataService.saveOrUpdateBatchById(datalist);
                       wsStationDataCurService.saveOrUpdateBatchById(list2);  //插入当前表
                   }
                   catch (Exception e){
                       log.error("和风处理过程中出现异常"+ e.getMessage());
                   }
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }

    public static LocalDateTime roundToNearestHour(LocalDateTime localDateTime) {
        // Get minutes and seconds
        int minutes = localDateTime.getMinute();
        int seconds = localDateTime.getSecond();

        // Determine rounding
        if (minutes >= 30) {
            // Round up
            return localDateTime.plusHours(1).withMinute(0).withSecond(0).withNano(0);
        } else {
            // Round down
            return localDateTime.withMinute(0).withSecond(0).withNano(0);
        }
    }
    /**
     * 天气预报
     * @param orgid
     */
    public void loadFcWeather(String orgid)  {
        SimpleDateFormat sdfresult = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat md = new SimpleDateFormat("MM-dd");
        try {
            LambdaQueryWrapper<WsStation> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WsStation::getStationtype,"4").likeRight(WsStation::getOrgid,orgid);
            List<WsStation>  weatherLocations =  wsStationService.list(queryWrapper);
            log.info("==============更新天气预报信息"+orgid+" ("+weatherLocations.size() + ")======================");
            for (WsStation w : weatherLocations) {
                WeatherFcResult weatherResult = new WeatherFcResult();
                String url = configBean.getWeahterfcurl() + "location={location}&key={key}";
                //设置请求头
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("location",w.getLon() + "," +w.getLat());
                paramMap.put("key",configBean.getKey());


                ResponseEntity<WeatherFcResult> responseEntity = restTemplate.getForEntity(url, WeatherFcResult.class,paramMap);

                weatherResult = responseEntity.getBody();
               if (weatherResult != null && weatherResult.getHourly().size() > 0) {
                    List<WsStationFcData> datalist = new ArrayList<WsStationFcData>();
                   List<WsStationFcDataCur> list2 = new ArrayList<WsStationFcDataCur>();
                    ZonedDateTime zonedTime = ZonedDateTime.parse(weatherResult.getUpdateTime());
                    LocalDateTime localTime = zonedTime.toLocalDateTime();
                    for (WeatherFcBean bean : weatherResult.getHourly()) {
                        try {
                            WsStationFcData ws = new WsStationFcData();
                            ws.setStationkey(w.getStationkey());
                            ws.setValidtimeMax(24); //24小时天气预报
                            ws.setPres(Float.parseFloat(bean.getPressure()));
                            ws.setHumi(Float.parseFloat(bean.getHumidity()));
                            ws.setPrec(Float.parseFloat(bean.getPrecip()));
                            ws.setWepTxt(bean.getText());
                            ws.setTemp(Float.parseFloat(bean.getTemp()));
                            ZonedDateTime zonedDateTime = ZonedDateTime.parse(bean.getFxTime());
                            LocalDateTime FcDateTime = zonedDateTime.toLocalDateTime();
                            ws.setFctime(FcDateTime);

                            long hours = Duration.between(localTime,FcDateTime).toHours() + 1;
                            ws.setTimebase(localTime);
                            ws.setValidtime((int)hours);
                            ws.setWinDir(Integer.parseInt(bean.getWind360()));
                            ws.setWinVel(Float.parseFloat(bean.getWindSpeed()));
                            String month = bean.getFxTime().replace("-", "");
                            month = month.substring(0, 6);
                            ws.setMonth(month);   //表分区月份 比填写
                            datalist.add(ws);

                            WsStationFcDataCur wsc = new WsStationFcDataCur();
                            try {
                                BeanUtils.copyProperties(wsc,ws);
                                list2.add(wsc);
                            } catch (Exception e) {

                            }

                        } catch (Exception e) {
                            log.error("和风处理过程中出现异常" + e.getMessage());
                        }
                    }
                    wsStationFcDataService.saveOrUpdateBatchById(datalist);
                    wsStationFcDataCurService.saveOrUpdateBatchById(list2);
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     * 查询有预警的城市信息
     */
    public List<WeatherWarningBean> loadwaringcity()  {
        try {
            WeatherWarningCityResult result = new WeatherWarningCityResult();
            String url = configBean.getWeatherwarningurl() + "&key={key}";
            //设置请求头
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("key", configBean.getKey());

            ResponseEntity<WeatherWarningCityResult> responseEntity = restTemplate.getForEntity(url, WeatherWarningCityResult.class, paramMap);
            result = responseEntity.getBody();
            return result.getWarningLocList();
        }
        catch (Exception e){
            return new ArrayList<WeatherWarningBean>();
        }
    }



    public void loadAlarm(WsStation wsStation)  {
        SimpleDateFormat sdfresult = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat ymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat md = new SimpleDateFormat("MM-dd");
        try {

            WeatherAlarmResult alarmResult = new WeatherAlarmResult();
                String url = configBean.getWeatheralarmurl() + "location={location}&key={key}";
                //设置请求头
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("location",wsStation.getStationkey());
                paramMap.put("key",configBean.getKey());

                ResponseEntity<WeatherAlarmResult> responseEntity = restTemplate.getForEntity(url, WeatherAlarmResult.class,paramMap);
                //   String str = responseEntity.getBody();
            alarmResult = responseEntity.getBody();
                if (alarmResult != null && alarmResult.getWarning() != null) {

                    for(WeatherAlarmBean alarmBean : alarmResult.getWarning()){
                        try {
                            List<WsAlarmData> datalist = new ArrayList<WsAlarmData>();

                            WsAlarmData ws = new WsAlarmData();
                            ws.setStationkey(wsStation.getStationkey());
                            ws.setId(alarmBean.getId());
                            ws.setName(alarmBean.getTitle());
                            ws.setContent(alarmBean.getText());

                            ZonedDateTime zonedDateTime = ZonedDateTime.parse(alarmBean.getStartTime());
                            LocalDateTime FcDateTime = zonedDateTime.toLocalDateTime();
                            ws.setStarttime(FcDateTime);

                            ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(alarmBean.getEndTime());
                            LocalDateTime FcDateTime2 = zonedDateTime2.toLocalDateTime();
                            ws.setEndtime(FcDateTime2);
                            ws.setCtime(LocalDateTime.now());

                            ZonedDateTime zonedDateTime3 = ZonedDateTime.parse(alarmBean.getPubTime());
                            LocalDateTime FcDateTime3 = zonedDateTime3.toLocalDateTime();
                            ws.setPubtime(FcDateTime3);


                            // 定义日期格式
                            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                            // 格式化日期
                            String formattedDate = LocalDateTime.now().format(formatter);
                            ws.setFxdate(formattedDate);
                            ws.setSender(alarmBean.getSender());
                            ws.setSeverity(alarmBean.getSeverity());
                            ws.setSeveritycolor(alarmBean.getSeverityColor());
                            ws.setStatus(alarmBean.getStatus());
                            ws.setType(alarmBean.getType());
                            ws.setTypename(alarmBean.getTypeName());
                            ws.setOrgid(wsStation.getOrgid()); //机构ID
                            datalist.add(ws);
                            wsAlarmDataService.saveOrUpdateBatch(datalist);
                        }
                        catch (Exception e){
                            log.error("和风处理预警过程中出现异常"+ e.getMessage());
                        }
                    }

                }
            }
        catch (Exception e){
            e.printStackTrace();
        }
    }





}
